package com.zpark.merchant.service.service.impl;

import com.alibaba.fastjson.JSON;
import com.zpark.jushanpay.common.domain.BusinessException;
import com.zpark.jushanpay.common.domain.CommonErrorCode;
import com.zpark.merchant.api.service.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 短信服务业务层接口实现类
 * 远程调用短信服务接口
 */
@Service
@Slf4j
public class SmsServiceImpl implements ISmsService {

    // 获取请求url
    @Value("${sms.url}")
    private String urlSms;

    // 获取验证码有效时间
    @Value("${sms.effectiveTime}")
    private Integer effectiveTime;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String sendMsg(String phone) {
        //验证码过期时间为600 秒 => 10分钟
        String url = urlSms + "/generate?name=sms&effectiveTime=" + effectiveTime;
        log.info("调用短信微服务发送验证码：url:{}", url);

        Map<String, Object> body = new HashMap< String, Object>();

        body.put("mobile", phone);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity entity = new HttpEntity(body, httpHeaders);

        Map responseMap;

        try {
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, entity,
                    Map.class);
            log.info("调用短信微服务发送验证码:返回值:{}", JSON.toJSONString(exchange));
            responseMap = exchange.getBody();
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("发送验证码出错");
        }
        if (responseMap == null || responseMap.get("result") == null) {
            throw new RuntimeException("发送验证码出错");
        }
        Map resultMap = (Map) responseMap.get("result");

        return resultMap.get("key").toString();
    }

    /**
     * 校验验证码
     * @param verifyCode 用户输入的验证码（6位纯数字）
     * @param verifyKey 商户应用平台的Key
     */
    @Override
    public void checkVerifyCode(String verifyCode, String verifyKey) throws BusinessException {
        // 定义请求的URL
        String url = urlSms + "/verify?name=sms&verificationKey=" + verifyKey
                + "&verificationCode=" + verifyCode;
        // 发起请求进行验证码校验
        Map responseMap = null;

        try {
            // 发起http请求校验验证码
            ResponseEntity<Map> response = restTemplate.postForEntity(url, null, Map.class);
            // 获取响应体数据
            responseMap = response.getBody();
            log.info("校验验证码，响应内容：{}",JSON.toJSONString(responseMap));
        } catch(Exception e) {
            e.printStackTrace();
            log.info(e.getMessage(), e);
            throw new BusinessException(CommonErrorCode.E_100102);
        }

        // 判断响应数据是否为空，为空则校验失败
        if (responseMap == null || responseMap.get("result") == null || !(Boolean)responseMap.get("result")) {
            throw new BusinessException(CommonErrorCode.E_100102);
        }

    }
}
